package kr.hyunist.androidcomplete01saeildamil.ch19;

import kr.hyunist.androidcomplete01saeildamil.*;
import android.app.*;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.os.*;
import android.view.*;
import android.widget.*;

public class BackWorkEx02 extends Activity {
	TextView mText;
	AccumThread mThread;
	ProgressDialog mProgress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.backworkex);

		mText = (TextView) findViewById(R.id.backworkstarttv);
	}

	@SuppressWarnings("deprecation")
	public void mOnClick(View v) {
		int start = 0, end = 100;

		mProgress = new ProgressDialog(BackWorkEx02.this);
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setTitle("Calcualting");
		mProgress.setMessage("Wait..");
		mProgress.setCancelable(false);
		mProgress.setButton("Cancel", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mThread.mQuit = true;
				mProgress.dismiss();
			}

		});
		mProgress.show();
		mThread = new AccumThread(start, end, mAfterAccum);
		mThread.start();
	}

	class AccumThread extends Thread {
		int mStart, mEnd;
		int mResult;
		Handler mAfter;
		boolean mQuit;

		public AccumThread(int start, int end, Handler after) {
			super();
			this.mStart = start;
			this.mEnd = end;
			this.mAfter = after;
			mQuit = false;
		}

		@Override
		public void run() {
			mResult = 0;
			for(int i = mStart; i <= mEnd; i++){
				mResult += i;
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					return;
				}
				mAfter.sendEmptyMessage(0);
			}
		}
		
	}
	
	Handler mAfterAccum = new Handler(){
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			if(mThread.mQuit == false){
				mText.setText("" + mThread.mResult);
			}
		};
	};
}
